package com.kkkk.rest.common.exception;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;


@Configuration
public class FeignErrorDecoder implements ErrorDecoder {
    private Logger logger = LoggerFactory.getLogger(FeignErrorDecoder.class);

    private String module;

    @Override
    public Exception decode(String s, Response response) {
        try {
            String message = Util.toString(response.body().asReader());
            JSONObject jsonObject = JSON.parseObject(message);
            if (jsonObject.get("status") != null) {
                return new AppException(String.valueOf(jsonObject.get("status")), jsonObject.getString("message"), jsonObject.getString("path"), jsonObject.getString("module"));
            } else {
                return new AppException(String.valueOf(jsonObject.get("code")), jsonObject.getString("message"), jsonObject.getString("fields"), jsonObject.getString("module"));
            }

        } catch (IOException e) {
            logger.error("error to decoder feignException", e);
        }
        AppException appException = new AppException(CommonErrorCodeEnum.FEIGN_EXCEPTION.getCode(), "error to decoder feignException");

        return appException;
    }
}
